package com.century.sjt.window;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.setting.Forget_pwdPayActivity;
//import com.century.sjt.activity.PaySuccessActivity;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.gridpasswordview.GridPasswordView;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

public class RechargePopupWindow extends PopupWindow {

    private Context mContext;

    private TextView forger_pwd;
    private GridPasswordView gpvCashPwd;
    private String ComeNumber;
    private Button btn_ok;
    private View mMenuView;

    private RequestQueue mQueue;
    private String type="3";

    private String cashPwd="";
    private String webHost="";

    public RechargePopupWindow(Activity context, View.OnClickListener itemsOnClick, final String Code, final String orderNo,
                                 String verificationCode, String Mobile) {
            super(context);
        mContext=context;

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.sjt_payok_item, null);
        Log.d("n00000000000000",Code+"*"+orderNo+"*"+verificationCode+"*"+"*"+Mobile+"!!!!!!");


        mQueue = Volley.newRequestQueue(mMenuView.getContext());
        gpvCashPwd=(GridPasswordView) mMenuView.findViewById(R.id.pay_cashpwd);

        btn_ok = (Button) mMenuView.findViewById(R.id.btn_payok);
        //确认按钮
        btn_ok.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                pay(Code,gpvCashPwd.getPassWord(),orderNo);
                //销毁弹出框
//                dismiss();
            }
        });
        //设置按钮监听

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.pop_layout).getTop();
                int y=(int) event.getY();
                if(event.getAction()==MotionEvent.ACTION_UP){
                    if(y<height){
                        dismiss();
                    }
                }
                return true;
            }
        });

        forger_pwd=(TextView) mMenuView.findViewById(R.id.sjt_forget_pwd);
        forger_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(mContext, Forget_pwdPayActivity.class);
                mContext.startActivity(intent);
            }
        });
        gpvCashPwd.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onChanged(String psw) {

            }

            @Override
            public void onMaxLength(String psw) {
                pay(Code,gpvCashPwd.getPassWord(),orderNo);

            }
        });
    }


    /**
     * 确认充值
     */
    private void pay(final String verificationCode, final String cashPwd,final String orderNo) {
        byte[] encodePwd = cashPwd.getBytes();
        final String pwd = Base64Utils.encode(encodePwd);
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,mContext. getResources().getString(R.string.error_please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.PayHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("确认充值接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject data = res.getJSONObject("data");
                        String newOrderNo = data.getString("orderNo");
//                        Intent intent = new Intent(mContext, PaySuccessActivity.class);
//                        Bundle t= new Bundle();
//                        t.putString("type", type);
//                        t.putString("orderNo",newOrderNo);
//                        //此处使用putExtras，接受方就响应的使用getExtra
//                        intent.putExtras( t );
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        mContext.startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                        dismiss();
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service),mContext, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("verificationCode", verificationCode);
                map.put("orderNo", orderNo);
                map.put("cashPwd", pwd);
                TipUtil.log("确认充值密码", pwd + "+" + gpvCashPwd.getPassWord(), 1);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }




}
